package com.ctnq.util;

import com.ctnq.aes.AES;
import com.ctnq.md5.MD5;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.xspace.android.xafcommon.util.LogUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class EncryptUtil {

    private final static EncryptUtil encryptUtil = new EncryptUtil();

    //私有构造函数
    private EncryptUtil() {

    }

    public synchronized static EncryptUtil getInstance() {
        return encryptUtil;
    }

    /**
     * 获取 加密签名
     *
     * @param
     * @return String md5code
     ****/
    public String getSignData(String dataStr) {

        String md5Code = "";
        try {
            md5Code = MD5.getMD5Code(AES.aesEncrypt(dataStr, AES.AES_KEY));
        } catch (Exception e) {

        }


        return md5Code;
    }


    /**
     * 加密数据
     *
     * @param encryptData 要加密的数据
     * @return String aesCode
     ****/
    public String getEncryptData(String encryptData) {
        String encrypt_after = "";
        try {
            encrypt_after = AES.aesEncrypt(encryptData, AES.AES_KEY);
        } catch (Exception e) {

            e.printStackTrace();
        }

        return encrypt_after;
    }


    /**
     * 解密数据
     *
     * @param decryptData 要解密的数据
     * @return String 解密后的数据
     ****/
    public String getDecryptData(String decryptData) throws Exception {
        return AES.aesDecrypt(decryptData, AES.AES_KEY);
    }

    /**
     * 校验签名
     *
     * @param client_sign,String server_sign
     * @return boolean 比对结果
     ****/
    public Boolean checkSignData(String client_sign, String server_sign) {

        return client_sign.equals(server_sign);
    }

    /**
     * 获取加密摘要数据
     *
     * @param json
     * @return String json
     ****/
    public String parseJSON2Str(String json) {
        Gson gson = new Gson();
//        Map<String, String> retMap = gson.fromJson(json,
//                new TypeToken<Map<String, String>>() {
//                }.getType());

        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            retMap = strJson2Map(json);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        LogUtil.v(retMap.toString());
        Map<String, Object> sortMap = sortMapByKey(retMap);
        LogUtil.v(sortMap.toString());
        StringBuffer returnValue = new StringBuffer();
        JsonParser parser = new JsonParser();
        String keyValue = "";
        JsonElement el = null;
        for (String key : sortMap.keySet()) {

            keyValue = parserJsonIsString(sortMap.get(key));
            returnValue.append(key).append("=").append(keyValue).append("&");
        }
        if (returnValue.length() > 1) {
            returnValue.deleteCharAt(returnValue.length() - 1);
        }
        LogUtil.v(returnValue.toString());
        return returnValue.toString();
    }

    public static String parserJsonIsString(Object json) {

        String returnStr = "";

        try {
            if (json instanceof String) {
                returnStr = String.valueOf(json);
            } else if (json instanceof Number) {
                double d = Double.valueOf(String.valueOf(json));
                returnStr = Integer.toString((int) d);
            }


        } catch (Exception e) {

            e.printStackTrace();
        }

        return returnStr;
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }

    public final static Map strJson2Map(String jsonStr) throws ParseException {
        JSONObject jsonObject = new JSONObject(jsonStr);
        return json2Map(jsonObject);
    }

    public final static Map json2Map(JSONObject jsonObject) {
        Map resultMap = new HashMap();
        Iterator iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            Object value = jsonObject.get(key);

            if (value instanceof JSONObject) {
                value = json2Map((JSONObject) value);
                resultMap.put(key, value);
            } else if (value instanceof JSONArray) {
                value = json2List((JSONArray) value);
                resultMap.put(key, value);
            } else {
                resultMap.put(key, jsonObject.getString(key));
            }
        }
        return resultMap;
    }

    public final static List json2List(JSONArray jsonArray) {
        List resultList = new ArrayList();
        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.get(i);
            if (value instanceof JSONObject) {
                value = json2Map((JSONObject) value);
            } else if (value instanceof JSONArray) {
                value = json2List((JSONArray) value);
            }
            resultList.add(value);
        }
        return resultList;
    }
}


//比较器类

class MapKeyComparator implements Comparator<String> {

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }

}
